import { Space, Button, Modal, List, Row, Col, message, Typography } from 'antd'
import React, { useState, useRef, useImperativeHandle, useEffect } from 'react'
import ConfigForm from '../config-form/index.jsx'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import {
  templatePageList,
  templateAttrSaveUpdate,
  templateDetailAttrList,
  deleteTemplateInfo
} from '@/api/base-config.js'
import './index.less'
import { cloneDeep } from 'lodash'
import { v4 as uuidv4 } from 'uuid'

export const ConfigAdd = React.forwardRef(
  ({ projectId, type, config, tableCom, showAdd, onRefresh, hideList }, ref) => {
    const { typeCode, typeName } = config
    const [isOpen, setIsOpen] = useState(false)

    const initRowData = () => {
      return {
        key: uuidv4(),
        projectId,
        templateType: typeCode,
        templateCode: '',
        templateName: '',
        templateIcon: '',
        typeId: type?.id??'',
        attrOrders: [],
      }
    }

    const [refreshFlag, setRefreshFlag] = useState(false)

    const [confirmLoading, setConfirmLoading] = useState(false)

    const [formValue, setFormValue] = useState(initRowData())

    const [templateData, setTemplateData] = useState([])

    const requestTemplateData = () => {
      templatePageList({ projectId: projectId, templateType: typeCode, pageSize: 10000 }).then(
        (res) => {
          const { data } = res
          let list = data.pageInfo.list
          setTemplateData(list)
        }
      )
    }

    const requestTemplateDetail = (templateId) => {
      templateDetailAttrList({ templateId }).then((res) => {
        let formValue = res.data
        formValue.key = uuidv4()
        formValue.attrOrders = formValue.attrResultList || []
        formValue.attrOrders.sort((a, b) => a.sortNum - b.sortNum)
        delete formValue.attrResultList
        setFormValue(formValue)
      })
    }

    const handleOpenModal = (editData) => {
      if (editData && editData.id) {
        requestTemplateDetail(editData.id)
      } else {
        setFormValue(initRowData())
      }

      setIsOpen(true)
    }

    // 方法暴露
    useImperativeHandle(
      ref,
      () => ({
        open(editData) {
          handleOpenModal(editData)
        },
      }),
      [type]
    )

    const configFormRef = useRef(null)

    const handleOk = () => {
      configFormRef.current
        .validateFields()
        .then((value) => {
          let menthod = templateAttrSaveUpdate
          const submitData = cloneDeep(value)
          submitData.attrOrders.forEach((item, index)=> {
            item.sortNum = index + 1
          })

          setConfirmLoading(true)
          menthod({typeId: type ? type.id : '',  ...formValue, ...submitData }).then(() => {
            message.success('保存成功')
            handleClearData()
            setConfirmLoading(false)

            if (hideList) {
              setIsOpen(false)
              onRefresh()
            } else {
              setRefreshFlag(true)
              requestTemplateData()
            }
          })
        })
        .catch(() => {
          setConfirmLoading(false)
        })
    }

    const handleCancel = () => {
      setIsOpen(false)
    }

    const handleClearData = () => {
      setFormValue(initRowData())
    }

    useEffect(() => {
      if (isOpen && !hideList) {
        requestTemplateData()
      } else {
        if (refreshFlag) {
          setRefreshFlag(false)
          onRefresh()
        }
      }
    }, [isOpen, hideList])

    const onDelete = (record, e) => {
      e.stopPropagation()
      deleteTemplateInfo({id: record.id, isConfirm: true}).then(() => {
        if(formValue && record.id == formValue.id) {
          handleClearData()
        }
        message.success('删除成功')
        requestTemplateData()
      })
    }

    return (
      <div className="config-pannel">
        {showAdd && (
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => handleOpenModal()}
            >
              新增
            </Button>
          </Space>
        )}

        <Modal
          centered
          width="95%"
          title={typeName + '配置'}
          open={isOpen}
          confirmLoading={confirmLoading}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Row className='config-add-content' gutter={12}>
            {!hideList && (
              <Col span={4}>
                <List
                  size="small"
                  bordered
                  dataSource={templateData}
                  renderItem={(item) => (
                    <List.Item className={formValue.id == item.id ? 'active' : ''} onClick={() => handleOpenModal(item)}>
                      <div className='flex-row space-between' style={{width: '100%'}}>
                        <div className='flex-1' style={{overflow: 'hidden'}}>
                          <Typography.Text ellipsis style={{width: '100%'}}>{item.templateName}</Typography.Text>
                        </div>
                        <Button
                            className='icon-btn'
                            type='text'
                            icon={<DeleteOutlined />}
                            size="small"
                            onClick={(e) => onDelete(item, e)}
                          />
                      </div>
                    </List.Item>
                  )}
                  style={{ width: '100%' }}
                />
              </Col>
            )}
            <Col span={ !hideList ? 20 : 24}>
              {
                !hideList && <div style={{ marginBottom: '10px' }}>
                  <Button size="small" type="primary" onClick={handleClearData}>
                    清除数据
                  </Button>
                </div>
              }
              <ConfigForm
                key={formValue.key}
                ref={configFormRef}
                config={config}
                value={formValue}
                onChange={setFormValue}
                tableCom={tableCom}
              />
            </Col>
          </Row>
        </Modal>
      </div>
    )
  }
)

ConfigAdd.displayName = 'ConfigAdd'

export default ConfigAdd
